<template>
  <div class="clazz-management">
    <div class="page-header">
      <h2>班级管理</h2>
    </div>

    <!-- 搜索表单 -->
    <el-card class="search-card" shadow="never">
      <el-form :model="searchForm" :inline="true" class="search-form">
        <el-form-item label="班级编号">
          <el-input v-model="searchForm.clazzNo" placeholder="请输入班级编号" clearable style="width: 200px" />
        </el-form-item>
        <el-form-item label="班级名称">
          <el-input v-model="searchForm.clazzName" placeholder="请输入班级名称" clearable style="width: 200px" />
        </el-form-item>
        <el-form-item label="年级">
          <el-input v-model="searchForm.grade" placeholder="请输入年级" clearable style="width: 160px" />
        </el-form-item>
        <el-form-item label="院系">
          <el-input v-model="searchForm.dept" placeholder="请输入院系" clearable style="width: 200px" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch"><el-icon><Search /></el-icon>搜索</el-button>
          <el-button @click="handleReset"><el-icon><Refresh /></el-icon>重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮 -->
    <el-card class="action-card" shadow="never">
      <div class="action-buttons">
        <el-button type="primary" @click="handleAdd"><el-icon><Plus /></el-icon>新增班级</el-button>
      </div>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card" shadow="never">
      <el-table :data="clazzList" v-loading="loading" stripe border style="width: 100%">
        <el-table-column prop="clazzNo" label="班级编号" width="120" />
        <el-table-column prop="clazzName" label="班级名称" width="160" />
        <el-table-column prop="grade" label="年级" width="100" />
        <el-table-column prop="dept" label="院系" width="160" />
        <el-table-column prop="teacherId" label="班主任ID" width="120" />
        <el-table-column prop="studentId" label="班长学生ID" width="120" />
        <el-table-column prop="remark" label="备注" min-width="200" />
        <el-table-column prop="updateDate" label="更新时间" width="160">
          <template #default="scope">{{ formatDate(scope.row.updateDate) }}</template>
        </el-table-column>
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="scope">
            <el-button type="info" size="small" @click="handleViewDetail(scope.row)">详情</el-button>
            <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10,20,50,100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="640px" @close="handleDialogClose">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="班级编号" prop="clazzNo">
          <el-input v-model="form.clazzNo" placeholder="请输入班级编号" />
        </el-form-item>
        <el-form-item label="班级名称" prop="clazzName">
          <el-input v-model="form.clazzName" placeholder="请输入班级名称" />
        </el-form-item>
        <el-form-item label="年级" prop="grade">
          <el-input v-model="form.grade" placeholder="请输入年级" />
        </el-form-item>
        <el-form-item label="院系" prop="dept">
          <el-input v-model="form.dept" placeholder="请输入院系" />
        </el-form-item>
        <el-form-item label="班主任ID" prop="teacherId">
          <el-input v-model.number="form.teacherId" placeholder="请输入班主任ID" />
        </el-form-item>
        <el-form-item label="班长学生ID" prop="studentId">
          <el-input v-model.number="form.studentId" placeholder="请输入班长学生ID" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" :rows="3" placeholder="请输入备注信息" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="班级详情" width="600px">
      <div class="detail-content">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="班级编号">{{ detailData.clazzNo }}</el-descriptions-item>
          <el-descriptions-item label="班级名称">{{ detailData.clazzName }}</el-descriptions-item>
          <el-descriptions-item label="年级">{{ detailData.grade }}</el-descriptions-item>
          <el-descriptions-item label="院系">{{ detailData.dept }}</el-descriptions-item>
          <el-descriptions-item label="班主任ID">{{ detailData.teacherId }}</el-descriptions-item>
          <el-descriptions-item label="班长学生ID">{{ detailData.studentId }}</el-descriptions-item>
          <el-descriptions-item label="更新时间" :span="2">{{ formatDate(detailData.updateDate) }}</el-descriptions-item>
          <el-descriptions-item label="备注" :span="2">{{ detailData.remark || '无' }}</el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
  
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus } from '@element-plus/icons-vue'
import { getClazzList, getClazzDetail, addClazz, updateClazz, deleteClazz } from '../api/clazz'

const searchForm = reactive({
  clazzNo: '',
  clazzName: '',
  grade: '',
  dept: ''
})

const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

const clazzList = ref([])
const loading = ref(false)

const dialogVisible = ref(false)
const dialogTitle = ref('')
const isEdit = ref(false)

const detailDialogVisible = ref(false)
const detailData = ref({})

const form = reactive({
  clazzId: null,
  clazzNo: '',
  clazzName: '',
  grade: '',
  dept: '',
  teacherId: null,
  studentId: null,
  remark: ''
})

const rules = {
  clazzNo: [{ required: true, message: '请输入班级编号', trigger: 'blur' }],
  clazzName: [{ required: true, message: '请输入班级名称', trigger: 'blur' }],
  grade: [{ required: true, message: '请输入年级', trigger: 'blur' }],
  dept: [{ required: true, message: '请输入院系', trigger: 'blur' }]
}

const formRef = ref()

const formatDate = (dateStr) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return date.toLocaleString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit' })
}

const handleSearch = () => {
  pagination.currentPage = 1
  fetchClazzList()
}

const handleReset = () => {
  Object.keys(searchForm).forEach(k => searchForm[k] = '')
  pagination.currentPage = 1
  fetchClazzList()
}

const handleAdd = () => {
  dialogTitle.value = '新增班级'
  isEdit.value = false
  resetForm()
  dialogVisible.value = true
}

const handleViewDetail = async (row) => {
  try {
    const response = await getClazzDetail(parseInt(row.clazzId))
    detailData.value = response.data || { ...row }
  } catch (e) {
    detailData.value = { ...row }
  }
  detailDialogVisible.value = true
}

const handleEdit = (row) => {
  dialogTitle.value = '编辑班级'
  isEdit.value = true
  Object.keys(form).forEach(k => form[k] = row[k] ?? (k.endsWith('Id') ? null : ''))
  dialogVisible.value = true
}

const handleDelete = (row) => {
  ElMessageBox.confirm(`确定要删除班级 "${row.clazzName}" 吗？`, '删除确认', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' })
    .then(async () => {
      await deleteClazz(parseInt(row.clazzId))
      ElMessage.success('删除成功')
      fetchClazzList()
    })
    .catch(() => ElMessage.info('已取消删除'))
}

const handleSubmit = async () => {
  const valid = await formRef.value.validate()
  if (!valid) return
  try {
    if (isEdit.value) {
      await updateClazz(form)
      ElMessage.success('编辑成功')
    } else {
      const { clazzId, ...addData } = form
      await addClazz(addData)
      ElMessage.success('新增成功')
    }
    dialogVisible.value = false
    fetchClazzList()
  } catch (e) {
    // 已由拦截器提示
  }
}

const handleDialogClose = () => {
  resetForm()
  formRef.value?.resetFields()
}

const resetForm = () => {
  Object.keys(form).forEach(k => form[k] = (k === 'clazzId' || k.endsWith('Id')) ? null : '')
}

const handleSizeChange = (val) => {
  pagination.pageSize = val
  pagination.currentPage = 1
  fetchClazzList()
}

const handleCurrentChange = (val) => {
  pagination.currentPage = val
  fetchClazzList()
}

const fetchClazzList = async () => {
  loading.value = true
  try {
    const params = {
      pageNum: pagination.currentPage,
      pageSize: pagination.pageSize,
      clazzNo: searchForm.clazzNo || '',
      clazzName: searchForm.clazzName || '',
      grade: searchForm.grade || '',
      dept: searchForm.dept || ''
    }
    const response = await getClazzList(params)
    if (response.data) {
      clazzList.value = response.data.records || response.data.list || []
      pagination.total = response.data.total || 0
    } else {
      clazzList.value = []
      pagination.total = 0
    }
  } finally {
    loading.value = false
  }
}

onMounted(() => fetchClazzList())
</script>

<style scoped>
.clazz-management { background: #f5f7fa; padding: 20px; font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif; box-sizing: border-box; }
.page-header { margin-bottom: 32px; text-align: center; }
.page-header h2 { margin: 0; color: #2c3e50; font-size: 28px; font-weight: 600; letter-spacing: 1px; }
.search-card { margin-bottom: 20px; border-radius: 8px; box-shadow: 0 2px 12px rgba(0,0,0,0.1); border: 1px solid #e4e7ed; background: #ffffff; }
.search-card :deep(.el-card__body) { padding: 20px; }
.search-form :deep(.el-form-item) { margin-bottom: 16px; margin-right: 24px; }
.action-card { margin-bottom: 20px; border-radius: 8px; box-shadow: 0 2px 12px rgba(0,0,0,0.1); border: 1px solid #e4e7ed; background: #ffffff; }
.action-card :deep(.el-card__body) { padding: 16px 20px; }
.action-buttons { display: flex; justify-content: flex-start; }
.table-card { border-radius: 8px; box-shadow: 0 2px 12px rgba(0,0,0,0.1); border: 1px solid #e4e7ed; background: #ffffff; overflow: hidden; }
.table-card :deep(.el-card__body) { padding: 0; }
.pagination-container { margin-top: 16px; padding: 16px 20px; display: flex; justify-content: center; background: #f5f7fa; border-top: 1px solid #ebeef5; }
</style>







